package com.management.department.teacherinfosystem.Controller;

import com.management.department.teacherinfosystem.Entity.User;
import com.management.department.teacherinfosystem.security.JwtProvider;
import com.management.department.teacherinfosystem.Service.UserService;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;

/**
 * 登录 / 登出 / token 刷新（可扩展）。
 */
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
@Validated
public class AuthController {

    private final AuthenticationManager authManager;
    private final JwtProvider jwtProvider;
    private final UserService userService;

    /**
     * 登录接口 —— 成功返回 token 与基础用户信息。
     */
    @PostMapping("/login")
    @Transactional(readOnly = true)
    public ResponseEntity<LoginResponse> login(@RequestBody @Validated LoginRequest req) {
        Authentication authentication = authManager.authenticate(
                new UsernamePasswordAuthenticationToken(req.getUsername(), req.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(authentication);

        User user = userService.findByUsername(req.getUsername()).orElseThrow();
        String token = jwtProvider.generateToken(user.getId(), user.getUsername());
        var roles = authentication.getAuthorities().stream()
                .map(a -> a.getAuthority())
                .toList();
        return ResponseEntity.ok(new LoginResponse(token, UserView.from(user), roles));
    }

    /* ===================== 注册（开放） ===================== */
    @PostMapping("/register")
    @Transactional
    public ResponseEntity<UserView> register(@RequestBody @Validated RegisterRequest req) {
        // 默认注册为 teacher 角色
        User u = userService.createUser(req.getUsername(), req.getPassword(), req.getName(),
                req.getDepartment(), "teacher");
        return ResponseEntity.ok(UserView.from(u));
    }
    /* -------------------- DTO / View -------------------- */

    @Data
    static class LoginRequest {
        @NotBlank
        private String username;
        @NotBlank
        private String password;
    }

    @Data
    static class RegisterRequest {
        @NotBlank private String username;
        @NotBlank @Size(min = 6) private String password;
        @NotBlank private String name;
        private String department;
    }
    @Data
    @AllArgsConstructor
    static class LoginResponse {
        private String token;
        private UserView user;
        private java.util.List<String> roles;
    }

    @Data
    @AllArgsConstructor
    static class UserView {
        private Long id;
        private String username;
        private String name;
        private String staffNo;
        private String department;

        static UserView from(User u) {
            return new UserView(u.getId(), u.getUsername(), u.getName(),
                    u.getStaffNo(), u.getDepartment());
        }
    }
}
